<template>
  <div class="app-container">
    <el-form
      ref="user"
      :model="user"
      :rules="validateRules"
      label-width="120px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="user.username" />
      </el-form-item>
      <el-form-item label="用户昵称">
        <el-input v-model="user.nickName" />
      </el-form-item>
      <el-form-item label="用户密码" prop="password">
        <el-input type="password" v-model="user.password" placeholder="输入新密码" />
      </el-form-item>
      <el-form-item label="用户头像">
        <div>
          <el-upload
            class="avatar-uploader center"
            :action="baseUrl + '/admin/oss/file/upload?host=cover'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="user.salt" :src="user.salt" class="avatar" />
            <el-icon v-else class="el-icon-plus avatar-uploader-icon"
              ><plus
            /></el-icon>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import userApi from '@/api/acl/user'
const defaultForm = {
  username: '',
  salt: '',
  nickName: '',
  password: '',
}
const validatePass = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error('密码不能小于6位'))
  } else {
    callback()
  }
}
export default {
  data() {
    return {
      baseUrl: process.env.BASE_API,
      user: defaultForm,
      saveBtnDisabled: false, // 保存按钮是否禁用,
      validateRules: {
        username: [
          {
            required: true,
            trigger: 'blur',
            message: '用户名必须输入',
          },
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePass,
          },
        ],
      },
    }
  },
  // 监听器
  watch: {
    $route(to, from) {
      this.init()
    },
  },
  // 生命周期方法（在路由切换，组件不变的情况下不会被调用）
  created() {
    this.init()
  },
  methods: {
    // 表单初始化
    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        // 对象拓展运算符：拷贝对象，而不是赋值对象的引用
        this.user = { ...defaultForm }
      }
    },
    saveOrUpdate() {
      this.$refs.user.validate((valid) => {
        if (valid) {
          this.saveBtnDisabled = true // 防止表单重复提交
          if (!this.user.id) {
            this.saveData()
          } else {
            this.updateData()
          }
        }
      })
    },
    // 新增讲师
    saveData() {
      userApi.save(this.user).then((response) => {
        if (response.success) {
          this.$message({
            type: 'success',
            message: response.message,
          })
          this.$router.push({ path: '/acl/user/list' })
        }
      })
    },
    // 根据id更新记录
    updateData() {
      // teacher数据的获取
      userApi.updateById(this.user).then((response) => {
        if (response.success) {
          this.$message({
            type: 'success',
            message: response.message,
          })
          this.$router.push({ path: '/acl/user/list' })
        }
      })
    },
    // 根据id查询记录
    fetchDataById(id) {
      userApi.getById(id).then((response) => {
        this.user = response.data.item
        this.user.password = ''
      })
    },
    handleAvatarSuccess(res, file) {
      this.user.salt = res.data.url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Avatar picture size can not exceed 2MB!')
      }
      return isLt2M
    },
  },
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>